package com.kwk.messagepushding.util;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

public class ModbusTcpCoilReader {
    public static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X ", b));
        }
        return sb.toString().trim();
    }

    public static byte[] createModbusRequest(String code) {
        byte[] transactionId = {(byte)Integer.parseInt(code.substring(0,2), 16), (byte)Integer.parseInt(code.substring(2,4), 16)}; // 事务标识符
        byte[] protocolId = {(byte)Integer.parseInt(code.substring(4,6), 16), (byte)Integer.parseInt(code.substring(6,8), 16)};    // 协议标识符
        byte[] length = {(byte)Integer.parseInt(code.substring(8,10), 16), (byte)Integer.parseInt(code.substring(10,12), 16)};     // 长度（包括单元标识符和功能码及数据）
        byte[] unitId = {(byte)Integer.parseInt(code.substring(12,14), 16)};              // 单元标识符
        byte[] functionCode = {(byte)Integer.parseInt(code.substring(14,16), 16)};        // 功能码（读保持寄存器）
        byte[] startAddress = {(byte)Integer.parseInt(code.substring(16,18), 16), (byte)Integer.parseInt(code.substring(18,20), 16)};  // 起始地址
        byte[] quantityOfRegisters = {(byte)Integer.parseInt(code.substring(20,22), 16), (byte)Integer.parseInt(code.substring(22,24), 16)}; // 寄存器数量

        byte[] request = new byte[transactionId.length + protocolId.length + length.length + unitId.length + functionCode.length + startAddress.length + quantityOfRegisters.length];
        System.arraycopy(transactionId, 0, request, 0, transactionId.length);
        System.arraycopy(protocolId, 0, request, transactionId.length, protocolId.length);
        System.arraycopy(length, 0, request, transactionId.length + protocolId.length, length.length);
        System.arraycopy(unitId, 0, request, transactionId.length + protocolId.length + length.length, unitId.length);
        System.arraycopy(functionCode, 0, request, transactionId.length + protocolId.length + length.length + unitId.length, functionCode.length);
        System.arraycopy(startAddress, 0, request, transactionId.length + protocolId.length + length.length + unitId.length + functionCode.length, startAddress.length);
        System.arraycopy(quantityOfRegisters, 0, request, transactionId.length + protocolId.length + length.length + unitId.length + functionCode.length + startAddress.length, quantityOfRegisters.length);
        return request;
    }

    public static String modbusTcpFunc(byte[] modbusRequest) {
        String serverAddress = "127.0.0.1"; // Modbus/TCP服务器地址
        int serverPort = 503;                   // Modbus/TCP服务器端口
        try (Socket socket = new Socket()) {
            socket.connect(new InetSocketAddress(serverAddress, serverPort));

            DataOutputStream output = new DataOutputStream(socket.getOutputStream());
            DataInputStream input = new DataInputStream(socket.getInputStream());

            output.write(modbusRequest);
            output.flush();

            // 读取响应（这里只是示例，未处理响应数据）
            int bytesRead;
            byte[] response = new byte[1024]; // 假设响应数据不会超过1024字节
            if((bytesRead = input.read(response)) != -1){
                byte[] data = new byte[bytesRead];
                System.arraycopy(response, 0, data, 0, bytesRead);
                // 打印接收到的数据（以十六进制形式）
                StringBuilder sb = new StringBuilder();
                for (byte b : data) {
                    sb.append(String.format("%02X ", b));
                }
                String readMsg = sb.toString().trim().replace(" ", "");
                return readMsg;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
